using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FytSoa.Service.DtoModel;
using FytSoa.Service.Interfaces;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using FytSoa.Common;
using FytSoa.Extensions;
using FytSoa.Core.Model;

namespace FytSoa.Api.Areas.Circle.Controllers
{
    [Route("api/circle/[controller]")]
    [ApiController]
    public class UserController:ControllerBase
    {
        private readonly IMemberService _memberService;
        public UserController(IMemberService memberService){
            _memberService=memberService;
        }

        /// <summary>
        /// 微信登录，根据code获得openid
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("openid")]
        public async Task<IActionResult> GetWxAppOpenIdByCode([FromBody]ParmString obj)
        {
            var wxres=await WxTools.GetOpenId(obj.parm);
            var res=new ApiResult<HttpWxRes>(){
                data=wxres
            };
            return Ok(res);
        }

        /// <summary>
        /// 微信用户直接登录或者注册
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("wxlogin")]
        public async Task<IActionResult> WxAppLoginAndReg([FromBody]Core.Model.Member.Member model)
        {
            var res=new ApiResult<MemberDto>();
            //先判断是否存在
            var dbRes=await _memberService.GetModelAsync(m=>m.OpenId==model.OpenId);
            if (dbRes.data!=null && !string.IsNullOrEmpty(dbRes.data.Guid))
            {
                //说明存在，直接登录
                res.data=new MemberDto(){
                    Guid=dbRes.data.Guid,
                    NickName=dbRes.data.NickName,
                    Point=dbRes.data.Point,
                    HeadPic=dbRes.data.HeadPic
                };
            }else{
                //不存在，来注册
                model.Guid=Guid.NewGuid().ToString();
                model.Grade="ce8691a1-2e7f-4866-abdc-36d0cb21aa97";
                model.LoginName="匿名："+Utils.Number(6);
                model.LoginPwd=DES3Encrypt.EncryptString("123456");
                model.RegTime=DateTime.Now;
                //保存到数据库
                await _memberService.AddAsync(model);

                res.data=new MemberDto(){
                    Guid=model.Guid,
                    NickName=model.NickName,
                    Point=model.Point,
                    HeadPic=model.HeadPic
                };
            }
            return Ok(res);
        }
    }
}
